#/usr/bin/python27
#-*- coding: utf-8 -*-
#  Copyright 2011-2013 wuweihui@cn.ibm.com
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import re
import os

from CIMLogParser import LogBase, LogListBase, simpledict

class LSLogItem(LogBase):
   """
   """
   def __init__(self, attrs, line, *args):
      LogBase.__init__(self, line, *args)
      self._attrs = attrs
      self._process_line(line)

   def _process_line(self, line):
      for i in range(len(self._attrs) - 1):
         k, si = self._attrs[i]
         nk, nsi = self._attrs[i+1]
         v = line[si:nsi-1].strip()
         self.__setattr__(k, v)
      
#   def __getkeyvalue__(self):
#      return (self.__hasattr__("ObjectId") and self.__getattribute__("ObjectId")) \
#             or (self.__hasattr__("Child") and self.__getattribute__("Child")) \
#             or (self.__hasattr__("DiscoveryId") and self.__getattribute__("DiscoveryId"))
#   

def refact_key(k):
   symbols = ['%', '^', '(', ')', '[', ']', '/']
   k = k.replace(' ', '_')
   for sn in symbols:
      k = k.replace(sn, '')
   return k

class LSLogItemList(LogListBase):
   _re_pattern = re.compile(r"\=+ Instance \d+ of (\w+)(\r\n\r\n|\n\n)(.*?)(\r\n\r\n|\n\n)", re.DOTALL)
   def __init__(self, output, *args):
      LogListBase.__init__(self, output, *args)
      self.attrs = []
      self._process_output(output)

   def _process_output(self, output):
      """
      """
      re_time = re.compile(r'Date/Time: (.*?)IBM DSCLI Version: (\d+\.\d+\.\d+\.\d+) DS:.*?')
      lines = output.splitlines()
      ret = re_time.match(lines[0])
      if not ret:
         raise RuntimeError("Unknown log format:\n" + output)
      self.clitime, self.cliversion = ret.groups()
      self.result = lines[1]
      if len(lines) <= 2:
         return
      re_splitline = re.compile(r'===+$')
      ret = re_splitline.match(lines[2])
      if not ret:
         #CMUC00025I mkfbvol: FB volume 0050 successfully created.
         #CMUC00025I mkfbvol: FB volume 0051 successfully created.
         self.result = '\n'.join(lines[1:])
         return
      self.attrs = self._get_attrs()
      for line in lines[3:]:
         self.append(LSLogItem(self.attrs, line))

   def _get_attrs(self):
      specail_attrs = ["Storage Unit", "DA Pair"]
      items = self.result.split()
      splitindexs = []
      si = 0
      for item in items:
         si = self.result.find(item, si)
         splitindexs.append(si)
      splitindexs.append(len(self.result)+1)
      i = len(items)
      while i > 0:
         i -= 1
         if items[i].startswith('('):
            items[i-1] = items[i-1] + "_" + items[i][1:-1]
            items.pop(i)
            splitindexs.pop(i)
         elif i > 0 and items[i-1] + ' ' + items[i] in specail_attrs:
            items[i-1] = items[i-1] + "_" + items[i]
            items.pop(i)
            splitindexs.pop(i)
      items.append('NULL')
      items = map(refact_key, items)
      return zip(items, splitindexs)
   
class ShowLogItem(LogBase):
   """
   """
   def __init__(self, output, *args):
      LogBase.__init__(self, output, *args)
      lines = output.splitlines()
      re_time = re.compile(r'Date/Time: (.*?)IBM DSCLI Version: (\d+\.\d+\.\d+\.\d+) DS:.*?')
      ret = re_time.match(lines[0])
      if not ret:
         raise RuntimeError("Unknown log format:\n" + output)
      self.clitime, self.cliversion = ret.groups()
      self._spi = self._get_split_index(lines)
      for line in lines[1:]:
         self._process_line(line)

   def _process_line(self, line):
      k = refact_key(line[:self._spi].strip())
      v = line[self._spi:].strip()
      self.__setattr__(k, v)
         
   def _get_split_index(self, lines):
      key_ids = ["ID"]
      index = 0
      for line in lines:
         items = line.split()
         if items[0] in key_ids:
            index = line.find(items[1], len(items[0]))
      if index == 0:
         raise RuntimeError("Show log parse Failed!\n" + self._output)
      return index
      
   
         